# -*- coding: utf-8 -*-

import json
from datetime import datetime
from odoo import http
from odoo.http import request
from .api_base import APIBaseController


class AnnouncementController(APIBaseController):
    """公告管理控制器"""
    
    def __init__(self):
        super().__init__()
        self.model_name = 'device.announcement'
    
    def get_json_data(self):
        """获取JSON请求数据"""
        try:
            return json.loads(request.httprequest.data.decode('utf-8'))
        except:
            return {}
    
    def log_operation(self, user_id, module, operation_type, content, **kwargs):
        """记录操作日志"""
        try:
            OperationLog = request.env['device.operation.log'].sudo()
            OperationLog.create_log(
                operator_id=user_id,
                module=module,
                operation_type=operation_type,
                content=content,
                **kwargs
            )
        except Exception as e:
            # 日志记录失败不影响主流程
            pass
    
    @http.route('/api/device/announcement/list', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    def get_announcement_list(self, **kwargs):
        """获取公告列表"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取查询参数
            page = int(kwargs.get('page', 1))
            limit = int(kwargs.get('limit', 10))
            keyword = kwargs.get('keyword', '')
            announcement_type = kwargs.get('type', '')
            status = kwargs.get('status', 'published')
            
            # 获取用户可见的公告
            Announcement = request.env['device.announcement'].sudo()
            announcements = Announcement.get_visible_announcements(user_id)
            
            # 添加过滤条件
            domain = []
            if keyword:
                domain.append('|')
                domain.append(('title', 'ilike', keyword))
                domain.append(('content', 'ilike', keyword))
            
            if announcement_type:
                domain.append(('announcement_type', '=', announcement_type))
            
            if status:
                domain.append(('status', '=', status))
            
            if domain:
                filtered_announcements = announcements.filtered_domain(domain)
            else:
                filtered_announcements = announcements
            
            # 分页
            total = len(filtered_announcements)
            start_index = (page - 1) * limit
            end_index = start_index + limit
            paged_announcements = filtered_announcements[start_index:end_index]
            
            # 格式化数据
            data = []
            for announcement in paged_announcements:
                is_read = user_id in announcement.read_user_ids.ids
                data.append({
                    'id': announcement.id,
                    'title': announcement.title,
                    'content': announcement.content,
                    'publisher_name': announcement.publisher_name,
                    'department_name': announcement.department_name,
                    'announcement_type': announcement.announcement_type,
                    'status': announcement.status,
                    'is_top': announcement.is_top,
                    'is_important': announcement.is_important,
                    'is_read': is_read,
                    'read_count': announcement.read_count,
                    'publish_date': announcement.publish_date.strftime('%Y-%m-%d %H:%M:%S') if announcement.publish_date else '',
                    'effective_date': announcement.effective_date.strftime('%Y-%m-%d %H:%M:%S') if announcement.effective_date else '',
                    'expire_date': announcement.expire_date.strftime('%Y-%m-%d %H:%M:%S') if announcement.expire_date else '',
                    'create_time': announcement.create_time.strftime('%Y-%m-%d %H:%M:%S') if announcement.create_time else ''
                })
            
            return self.success_response('获取成功', {
                'list': data,
                'total': total,
                'page': page,
                'limit': limit,
                'pages': (total + limit - 1) // limit
            })
            
        except Exception as e:
            return self.error_response(f'获取公告列表失败: {str(e)}')
    
    @http.route('/api/device/announcement/detail/<int:announcement_id>', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    def get_announcement_detail(self, announcement_id, **kwargs):
        """获取公告详情"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取公告详情
            Announcement = request.env['device.announcement'].sudo()
            announcement = Announcement.browse(announcement_id)
            
            if not announcement.exists():
                return self.error_response('公告不存在', 404)
            
            # 检查是否有查看权限
            visible_announcements = Announcement.get_visible_announcements(user_id)
            if announcement.id not in visible_announcements.ids:
                return self.error_response('无权限查看该公告', 403)
            
            # 标记为已读
            announcement.action_mark_as_read(user_id)
            
            # 格式化数据
            is_read = user_id in announcement.read_user_ids.ids
            data = {
                'id': announcement.id,
                'title': announcement.title,
                'content': announcement.content,
                'publisher_name': announcement.publisher_name,
                'department_name': announcement.department_name,
                'announcement_type': announcement.announcement_type,
                'status': announcement.status,
                'visibility_scope': announcement.visibility_scope,
                'is_top': announcement.is_top,
                'is_important': announcement.is_important,
                'is_read': is_read,
                'read_count': announcement.read_count,
                'read_user_count': announcement.read_user_count,
                'publish_date': announcement.publish_date.strftime('%Y-%m-%d %H:%M:%S') if announcement.publish_date else '',
                'effective_date': announcement.effective_date.strftime('%Y-%m-%d %H:%M:%S') if announcement.effective_date else '',
                'expire_date': announcement.expire_date.strftime('%Y-%m-%d %H:%M:%S') if announcement.expire_date else '',
                'create_time': announcement.create_time.strftime('%Y-%m-%d %H:%M:%S') if announcement.create_time else '',
                'remark': announcement.remark or ''
            }
            
            return self.success_response('获取成功', data)
            
        except Exception as e:
            return self.error_response(f'获取公告详情失败: {str(e)}')
    
    @http.route('/api/device/announcement/unread-count', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    def get_unread_count(self, **kwargs):
        """获取未读公告数量"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取未读数量
            Announcement = request.env['device.announcement'].sudo()
            unread_count = Announcement.get_unread_count(user_id)
            
            return self.success_response('获取成功', {'unread_count': unread_count})
            
        except Exception as e:
            return self.error_response(f'获取未读数量失败: {str(e)}')
    
    @http.route('/api/device/announcement/mark-read', type='http', auth='none', methods=['POST'], csrf=False, cors='*')
    def mark_as_read(self, **kwargs):
        """标记公告为已读"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取请求数据
            data = self.get_json_data()
            announcement_id = data.get('announcement_id')
            
            if not announcement_id:
                return self.error_response('缺少公告ID参数')
            
            # 标记为已读
            Announcement = request.env['device.announcement'].sudo()
            announcement = Announcement.browse(announcement_id)
            
            if not announcement.exists():
                return self.error_response('公告不存在', 404)
            
            announcement.action_mark_as_read(user_id)
            
            return self.success_response('标记成功')
            
        except Exception as e:
            return self.error_response(f'标记失败: {str(e)}')
    
    @http.route('/api/device/announcement/create', type='http', auth='none', methods=['POST'], csrf=False, cors='*')
    def create_announcement(self, **kwargs):
        """创建公告"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 检查发布权限
            Announcement = request.env['device.announcement'].sudo()
            if not Announcement.check_publish_permission(user_id):
                return self.error_response('无权限发布公告', 403)
            
            # 获取请求数据
            data = self.get_json_data()
            required_fields = ['title', 'content']
            
            # 验证必填字段
            for field in required_fields:
                if not data.get(field):
                    return self.error_response(f'缺少必填字段: {field}')
            
            # 准备创建数据
            User = request.env['device.user'].sudo()
            current_user = User.browse(user_id)
            
            vals = {
                'title': data['title'],
                'content': data['content'],
                'publisher_id': user_id,
                'department_id': current_user.department_id.id if current_user.department_id else False,
                'announcement_type': data.get('announcement_type', 'normal'),
                'visibility_scope': data.get('visibility_scope', 'department'),
                'is_top': data.get('is_top', False),
                'is_important': data.get('is_important', False),
                'effective_date': data.get('effective_date', datetime.now()),
                'expire_date': data.get('expire_date'),
                'remark': data.get('remark', '')
            }
            
            # 处理时间字段
            if data.get('effective_date'):
                try:
                    vals['effective_date'] = datetime.strptime(data['effective_date'], '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    vals['effective_date'] = datetime.strptime(data['effective_date'], '%Y-%m-%d')
            
            if data.get('expire_date'):
                try:
                    vals['expire_date'] = datetime.strptime(data['expire_date'], '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    vals['expire_date'] = datetime.strptime(data['expire_date'], '%Y-%m-%d')
            
            # 创建公告
            announcement = Announcement.create(vals)
            
            # 如果设置为立即发布
            if data.get('auto_publish', False):
                announcement.action_publish()
            
            # 记录操作日志
            self.log_operation(
                user_id, 'announcement', 'create',
                f'创建公告: {announcement.title}',
                target_model='device.announcement',
                target_id=announcement.id,
                target_name=announcement.title
            )
            
            return self.success_response('创建成功', {'id': announcement.id})
            
        except Exception as e:
            return self.error_response(f'创建公告失败: {str(e)}')
    
    @http.route('/api/device/announcement/update/<int:announcement_id>', type='http', auth='none', methods=['PUT'], csrf=False, cors='*')
    def update_announcement(self, announcement_id, **kwargs):
        """更新公告"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取公告
            Announcement = request.env['device.announcement'].sudo()
            announcement = Announcement.browse(announcement_id)
            
            if not announcement.exists():
                return self.error_response('公告不存在', 404)
            
            # 检查修改权限（只有发布者或管理员可以修改）
            User = request.env['device.user'].sudo()
            current_user = User.browse(user_id)
            
            if not (current_user.is_admin or announcement.publisher_id.id == user_id):
                return self.error_response('无权限修改该公告', 403)
            
            # 获取请求数据
            data = self.get_json_data()
            
            # 准备更新数据
            vals = {}
            updatable_fields = ['title', 'content', 'announcement_type', 'visibility_scope', 
                              'is_top', 'is_important', 'effective_date', 'expire_date', 'remark']
            
            for field in updatable_fields:
                if field in data:
                    vals[field] = data[field]
            
            # 处理时间字段
            if 'effective_date' in data and data['effective_date']:
                try:
                    vals['effective_date'] = datetime.strptime(data['effective_date'], '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    vals['effective_date'] = datetime.strptime(data['effective_date'], '%Y-%m-%d')
            
            if 'expire_date' in data and data['expire_date']:
                try:
                    vals['expire_date'] = datetime.strptime(data['expire_date'], '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    vals['expire_date'] = datetime.strptime(data['expire_date'], '%Y-%m-%d')
            
            # 更新公告
            announcement.write(vals)
            
            # 记录操作日志
            self.log_operation(
                user_id, 'announcement', 'update',
                f'更新公告: {announcement.title}',
                target_model='device.announcement',
                target_id=announcement.id,
                target_name=announcement.title
            )
            
            return self.success_response('更新成功')
            
        except Exception as e:
            return self.error_response(f'更新公告失败: {str(e)}')
    
    @http.route('/api/device/announcement/publish/<int:announcement_id>', type='http', auth='none', methods=['POST'], csrf=False, cors='*')
    def publish_announcement(self, announcement_id, **kwargs):
        """发布公告"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取公告
            Announcement = request.env['device.announcement'].sudo()
            announcement = Announcement.browse(announcement_id)
            
            if not announcement.exists():
                return self.error_response('公告不存在', 404)
            
            # 检查发布权限
            User = request.env['device.user'].sudo()
            current_user = User.browse(user_id)
            
            if not (current_user.is_admin or announcement.publisher_id.id == user_id):
                return self.error_response('无权限发布该公告', 403)
            
            # 发布公告
            announcement.action_publish()
            
            # 记录操作日志
            self.log_operation(
                user_id, 'announcement', 'update',
                f'发布公告: {announcement.title}',
                target_model='device.announcement',
                target_id=announcement.id,
                target_name=announcement.title
            )
            
            return self.success_response('发布成功')
            
        except Exception as e:
            return self.error_response(f'发布公告失败: {str(e)}')
    
    @http.route('/api/device/announcement/withdraw/<int:announcement_id>', type='http', auth='none', methods=['POST'], csrf=False, cors='*')
    def withdraw_announcement(self, announcement_id, **kwargs):
        """撤回公告"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取公告
            Announcement = request.env['device.announcement'].sudo()
            announcement = Announcement.browse(announcement_id)
            
            if not announcement.exists():
                return self.error_response('公告不存在', 404)
            
            # 检查撤回权限
            User = request.env['device.user'].sudo()
            current_user = User.browse(user_id)
            
            if not (current_user.is_admin or announcement.publisher_id.id == user_id):
                return self.error_response('无权限撤回该公告', 403)
            
            # 撤回公告
            announcement.action_withdraw()
            
            # 记录操作日志
            self.log_operation(
                user_id, 'announcement', 'update',
                f'撤回公告: {announcement.title}',
                target_model='device.announcement',
                target_id=announcement.id,
                target_name=announcement.title
            )
            
            return self.success_response('撤回成功')
            
        except Exception as e:
            return self.error_response(f'撤回公告失败: {str(e)}')
    
    @http.route('/api/device/announcement/delete/<int:announcement_id>', type='http', auth='none', methods=['DELETE'], csrf=False, cors='*')
    def delete_announcement(self, announcement_id, **kwargs):
        """删除公告"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return self.error_response('未授权访问', 401)
            
            user_id = current_user.id
            
            # 获取公告
            Announcement = request.env['device.announcement'].sudo()
            announcement = Announcement.browse(announcement_id)
            
            if not announcement.exists():
                return self.error_response('公告不存在', 404)
            
            # 检查删除权限（只有管理员或发布者可以删除）
            User = request.env['device.user'].sudo()
            current_user = User.browse(user_id)
            
            if not (current_user.is_admin or announcement.publisher_id.id == user_id):
                return self.error_response('无权限删除该公告', 403)
            
            announcement_title = announcement.title
            
            # 删除公告
            announcement.unlink()
            
            # 记录操作日志
            self.log_operation(
                user_id, 'announcement', 'delete',
                f'删除公告: {announcement_title}',
                target_model='device.announcement',
                target_id=announcement_id,
                target_name=announcement_title
            )
            
            return self.success_response('删除成功')
            
        except Exception as e:
            return self.error_response(f'删除公告失败: {str(e)}')
